//
//  UIImage+Rotate.m
//  IphoneMapSdkDemo
//
//  Created by wzy on 14-11-14.
//  Copyright (c) 2014年 Baidu. All rights reserved.
//

#import <objc/runtime.h>
// 当前iOS版本
#ifndef __CUR_IOS_VERSION
#define __CUR_IOS_VERSION ([[[UIDevice currentDevice] systemVersion] floatValue] * 10000)
#endif

#import "UIImage+Rotate.h"

@implementation UIImage (Rotate)

- (UIImage*)imageRotatedByDegrees:(CGFloat)degrees {
    
    CGFloat width = CGImageGetWidth(self.CGImage);
    CGFloat height = CGImageGetHeight(self.CGImage);
    
    CGSize rotatedSize;
    
    rotatedSize.width = width;
    rotatedSize.height = height;
    
    UIGraphicsBeginImageContext(rotatedSize);
    CGContextRef bitmap = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(bitmap, rotatedSize.width/2, rotatedSize.height/2);
    CGContextRotateCTM(bitmap, degrees * M_PI / 180);
    CGContextRotateCTM(bitmap, M_PI);
    CGContextScaleCTM(bitmap, -1.0, 1.0);
    CGContextDrawImage(bitmap, CGRectMake(-rotatedSize.width/2, -rotatedSize.height/2, rotatedSize.width, rotatedSize.height), self.CGImage);
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}


@end



@implementation UIImage (LocalImage)

+ (void)load {
    if (__CUR_IOS_VERSION >= __IPHONE_8_0) {
        // 由于iOS8已经兼容，所以不需要使用下面方法
        return;
    }
    
    // 改替换实现用代码调用imageNamed:时的图片适应
    SEL origM = @selector(imageNamed:);
    SEL newM = @selector(imageWithName:);
    method_exchangeImplementations(class_getClassMethod(self, origM), class_getClassMethod(self, newM));
    
    // 该替换实现对xib中图片的适应
    NSString *className = [[@"UIImage" stringByAppendingString:@"Nib"] stringByAppendingString:@"Placeholder"]; // 这样写是为了避开AppStore审核的代码检查，不一定有效
    Method m1 = class_getInstanceMethod(NSClassFromString(className), @selector(initWithCoder:));
    Method m2 = class_getInstanceMethod(self, @selector(initWithCoderForNib:));
    method_exchangeImplementations(m1, m2);
    
}

/// 该方法替换原有的imageNamed:方法
+ (UIImage *)imageWithName:(NSString *)name {
    UIImage *aImage = [self imageWithName:name];
    if (aImage) {
        // 如果能取到对应图片，则直接返回
        return aImage;
    }
    
    NSString *fileName = [name stringByAppendingString:@"@3x.png"];
    aImage = [UIImage imageWithContentsOfFile:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:fileName]];
    
    return [aImage scaledImageFrom3x];
}

/** 该方法替换UIImage-Nib-Placeholder中的initWithCoder:，因为xib的图片都是用这个类来初始化的 */
- (id)initWithCoderForNib:(NSCoder *)aDecoder
{
    NSString *resourceName = [aDecoder decodeObjectForKey:@"UIResourceName"];
    NSString *newResourceName = resourceName;
    
    if ([resourceName hasSuffix:@".png"]) {
        newResourceName = [resourceName substringToIndex:resourceName.length -4];
    }
    
    return [UIImage imageNamed:newResourceName];
}
/** 将原本3倍尺寸的图片缩放到设备对应尺寸 */
- (UIImage *)scaledImageFrom3x
{
    float locScale = [UIScreen mainScreen].scale;
    
    float theRate = 1.0 / 3.0;
    UIImage *newImage = nil;
    
    CGSize oldSize = self.size;
    
    CGFloat scaledWidth = oldSize.width * theRate;
    CGFloat scaledHeight = oldSize.height * theRate;
    
    CGRect scaledRect = CGRectZero;
    scaledRect.size.width  = scaledWidth;
    scaledRect.size.height = scaledHeight;
    
    UIGraphicsBeginImageContextWithOptions(scaledRect.size, NO, locScale);
    
    [self drawInRect:scaledRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    if(newImage == nil) {
        NSLog(@"could not scale image");
    }
    
    return newImage;
}

@end



@implementation UIImage(AutoResize)

// 创建目录
+ (BOOL)createDirectory:(NSString*)directory {
    NSError* error = nil;
    BOOL isCreatDirSucc = [[NSFileManager defaultManager] createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:nil error:&error];
    if (!isCreatDirSucc && !error) {
        NSLog(@"创建%@目录失败：%@", directory, error);
        return NO;
    } else {
        NSLog(@"创建%@目录成功", directory);
        return YES;
    }
}

// 检测目录是否存在
+ (BOOL)isDirectoryExist:(NSString*)directory {
    BOOL isDir = NO;
    
    // 如果目录不存在则创建目录
    BOOL isDirExist = [[NSFileManager defaultManager] fileExistsAtPath:directory isDirectory:&isDir];
    if (!isDirExist && !isDir) {
        if ([self createDirectory:directory] == NO) {
            return NO;
        }
    }
    isDirExist = [[NSFileManager defaultManager] fileExistsAtPath:directory];
    
    return isDirExist;
}

+ (UIImage*)originImage:(UIImage *)image scaleToSize:(CGSize)size
{
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    
    // 绘制改变大小的图片
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    
    // 返回新的改变大小后的图片
    return scaledImage;
}

// 按照倍数缩放
+ (UIImage*)originImage:(UIImage *)image scaleWithMultiple:(CGFloat)multiple {
    CGSize size = image.size;
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    
    // 绘制改变大小的图片
    [image drawInRect:CGRectMake(0, 0, size.width * multiple, size.height * multiple)];
    
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
 
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    
    // 返回新的改变大小后的图片
    return scaledImage;
}

// /Users/mysj/Desktop/


- (void)generateSuitImagesWithOriginImagePath:(NSString*)originPath
                                 newImagePath:(NSString*)newPath
                              originImageType:(DOTOriginImageType)originImageType
                     autoGenerateEnLargeImage:(BOOL)enLarge
{
    NSFileManager* fileManager = [NSFileManager defaultManager];
    
    
    BOOL isDir = NO;
    BOOL isDirExist = [fileManager fileExistsAtPath:originPath isDirectory:&isDir];
    
    if (isDir == NO || isDirExist == NO) {
        NSLog(@"%@ %@不存在", NSStringFromClass([self class]), originPath);
        return;
    }
    
    NSString* newImagePath = [NSString stringWithFormat:@"%@", newPath];
    NSLog(@"%@", newImagePath);
    if (newPath == nil || newPath.length == 0) {
        newImagePath = [originPath stringByAppendingPathComponent:@"newImages"];
    }
    
    // 判读目录是否存在 不存在则创建
    if ([self.class isDirectoryExist:newImagePath] == NO) {
        NSLog(@"%@ %@不存", NSStringFromClass([self class]), newImagePath);
        return;
    }
    
    NSString* tmpImagePath = [newImagePath stringByAppendingPathComponent:@"tmp"];
    if ([self.class isDirectoryExist:tmpImagePath] == NO) {
        NSLog(@"%@ 创建临时目录[%@]失败", NSStringFromClass([self class]), tmpImagePath);
        return;
    }
    
    // 遍历目录下的文件
    NSDirectoryEnumerator* direnum = [fileManager enumeratorAtPath:originPath];
    NSMutableArray *files = [NSMutableArray array];
    NSString *filename ;
    while (filename = [direnum nextObject]) {
        if ([[filename pathExtension] isEqualToString:@"png"]) {
            [files addObject: filename];
        }
    }
    
//    NSLog(@"%@ %@", NSStringFromClass([self class]), files);
    
    for (NSString* filename in files) {
        NSString* prefix = [[filename componentsSeparatedByString:@"."] objectAtIndex:0];
        
        
        NSString* filePrefix = [NSString stringWithString:prefix];
        NSRange range = [prefix rangeOfString:@"@"];
        if (range.length != 0) {
            //如果包含@符号 剔除 @3x, @2x等字符
            filePrefix = [[prefix componentsSeparatedByString:@"@"] objectAtIndex:0];
        }
        
        
        // 临时目录
        NSString* oldPath = [originPath stringByAppendingPathComponent:filename];
        NSString* tmpNewImagePath = [[tmpImagePath stringByAppendingPathComponent:filePrefix] stringByAppendingPathExtension:@"png"];
//        NSLog(@"%@   原图片名", filePrefix);
        NSString* bigPath = [[newImagePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@@3x", filePrefix]] stringByAppendingPathExtension:@"png"];
        NSString* middlePath = [[newImagePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@@2x", filePrefix]] stringByAppendingPathExtension:@"png"];
        NSString* smallPath = [[newImagePath stringByAppendingPathComponent:filePrefix] stringByAppendingPathExtension:@"png"];
        
//        NSLog(@"原图路径 %@",oldPath);
//        NSLog(@" %@", tmpNewImagePath);
        /*
         必须先将 图片名中包含@3x/@2x的图片移动并重命名为没有@3x/@2x的图片（如果不重命名，会导致计算加载正确的图片），然后再缩放
         
         涉及到UIImage加载行为
         */
        NSError* error = nil;
        
        BOOL copySucc = [[NSFileManager defaultManager] copyItemAtPath:oldPath toPath:tmpNewImagePath error:&error];
        if (copySucc && error == nil) {
            if (originImageType == DOTOriginImageType3x) {
                [self.class saveResizedImageWithOriginPath:tmpNewImagePath toNewPath:bigPath WithMultiple:1.0];
                [self.class saveResizedImageWithOriginPath:tmpNewImagePath toNewPath:middlePath WithMultiple:0.667];
                [self.class saveResizedImageWithOriginPath:tmpNewImagePath toNewPath:smallPath WithMultiple:0.334];
                
            } else if (originImageType ==DOTOriginImageType2x) {
                [self.class saveResizedImageWithOriginPath:tmpNewImagePath toNewPath:middlePath WithMultiple:1.0];
                [self.class saveResizedImageWithOriginPath:tmpNewImagePath toNewPath:smallPath WithMultiple:0.5];
                [self.class saveResizedImageWithOriginPath:tmpNewImagePath toNewPath:bigPath WithMultiple:1.5];
            }
            
        }
    }
}

+ (BOOL)saveResizedImageWithOriginPath:(NSString*)originPath toNewPath:(NSString*)newPath WithMultiple:(CGFloat)multiple {
    
    UIImage* originImage = [UIImage imageNamed:originPath];
    
    CGSize newSize = CGSizeMake(originImage.size.width * multiple, originImage.size.height * multiple);
    UIImage* newImage = [self originImage:originImage scaleToSize:newSize];
    
    BOOL scaleSucc = [UIImagePNGRepresentation(newImage) writeToFile:newPath atomically:YES];
    if (scaleSucc == YES) {
//        NSLog(@"%lf:%@---->%@成功", multiple, originPath, newPath);
    }
    return scaleSucc;
}

@end
